package util.thread.creatthread;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Runnable 方式创建线程
 *
 * @author: Lidong
 * @time: 2020/8/6 20:55
 **/
public class CreateThreadByRunnableTest {

    private static final Logger logger = LoggerFactory.getLogger(CreateThreadByRunnableTest.class);
    private static final int TICKET_NUM = 11;

    /**
     * 使用 Runnable 的方式创建代码可以达到相同代码公用共同的资源
     */
    @Test
    public void test() {
        int num = 10;
        BuyTicketsRunnable buyTicketsRunnable = new BuyTicketsRunnable(num);
        for (int i = 0; i < TICKET_NUM; i++) {
            Thread thread = new Thread(buyTicketsRunnable);
            thread.start();
            if (Thread.holdsLock(Thread.currentThread())) {
                logger.info("当前线程持有对象监视器！");
            }
        }
    }

    class BuyTicketsRunnable implements Runnable {

        private final Logger logger = LoggerFactory.getLogger(BuyTicketsRunnable.class);

        private int num;

        BuyTicketsRunnable(int ticketNum) {
            this.num = ticketNum;
        }

        @Override
        public void run() {
            synchronized (this) {
                if (num > 0) {
                    num--;
                    logger.info("Thread {} 买到一张票 还剩：{} 张票", Thread.currentThread().getId(), num);
                } else {
                    logger.info("Thread {} 没有抢到票 还剩：{} 张票", Thread.currentThread().getId(), num);
                }
            }
        }

    }

}

